//
//  HMStatusListViewModel.swift
//  HMWeibo
//
//  Created by wulei on 15/12/11.
//  Copyright © 2015年 wulei. All rights reserved.
//

import Foundation
import SDWebImage
class HMStatusListViewModel {
/// 微博数据数组 上拉/下拉刷新
    lazy var statusList = [HMStatusViewModel]()
    
    /// 加载数据
    func loadStatus(isPullup isPullup: Bool,finish: (isSuccess: Bool) -> ()) {
        
        // 下拉刷新: 获取数组中第一条数据的ID
        let since_id = isPullup ? 0 :(statusList.first?.status.id ?? 0)
        let max_id = isPullup ? (statusList.last?.status.id ?? 0) : 0
        
        
        HMNetworkTools.sharedTools.loadStatus(since_id: since_id, max_id: max_id) { (result, error) -> () in
            if  error != nil {

                finish(isSuccess: false)
                return
            }
            
            // 判断result 数扰格式是否正确
            guard let array = result!["statuses"] as? [[String: AnyObject]] else {

                finish(isSuccess: false)
                return
            }
            
            // 可变数组
            var dataList = [HMStatusViewModel]()
            
            // 遍历数组
            for dict in array {
                
                dataList.append(HMStatusViewModel(status: HMStatus(dict: dict)))
            }
            
            print("刷新到\(dataList.count)条数据")
            
            // 拼接数据
            
            if max_id > 0 {
                self.statusList += dataList
            } else {
                
                self.statusList = dataList + self.statusList
            }
            
//            finish(isSuccess: true)
            self.cacheSingleImage(dataList, finish: finish)
        }
    }
    
    // 下载单张图片
    func cacheSingleImage(dataList: [HMStatusViewModel],finish: (isSuccess: Bool) -> ()){

        
        // 创建调度组
        let group = dispatch_group_create()
        // 数据长度
        var dataLength = 0
        
        
        // 1.拿到模型遍历
        for vm in dataList {
         
            if vm.thumbnailUrls?.count != 1{
                continue
            }
            
            let URL = vm.thumbnailUrls?[0]
            
//            print("开始缓存图像\(URL)")
            
            // SDWebImage 下载图像缓存都是自动完成的
            // 入组,监听后续的Block
            dispatch_group_enter(group)
            
            
            // 进行下载
            // SDWebImage 的核心下载函数,如果本地函数已存在,同样会通过完成回调返回
           SDWebImageManager.sharedManager().downloadImageWithURL(URL, options: [], progress: nil, completed: { (image, _, _, _, _) -> Void in
            
            
            if let img = image, let data = UIImagePNGRepresentation(img) {
                dataLength += data.length
            }
            
            dispatch_group_leave(group)
           })
            
            
        }
        
        // 监听调度组完成
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
//            print("缓存完成\(dataLength / 1024)k")
            finish(isSuccess: true)
        }
        
        
        
        
       
        
        
        
        
        
    }
    
    
}
